package com.lhsy.djcloud.controller;

import com.lhsy.djcloud.common.FileUpload;
import com.lhsy.djcloud.common.ReturnT;
import com.lhsy.djcloud.entity.Upload;
import com.lhsy.djcloud.entity.User;
import com.lhsy.djcloud.entity.dto.UserDto;
import com.lhsy.djcloud.service.UploadService;
import com.lhsy.djcloud.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author wzw
 * @Date: 2020/10/13 2018/11/02
 */
@RestController
@RequestMapping("/upload")
@Api(value = "Server-API",tags = "文件上传接口")
@Slf4j
public class UploadController  extends BaseController{

    @Autowired
    private UploadService uploadService;
    @Autowired
    private UserService userService;
    /**
     * 上传web格式图片
     */
    @PostMapping("/file")
    @ApiOperation(value = "文件上传")
    public ReturnT uploadImage(HttpServletRequest request,@RequestParam("file") MultipartFile multipartFile, @RequestParam(value = "type",required = false) Integer type) {
        log.info("开始上传文件:name[{}] size[{}]",multipartFile.getOriginalFilename(),multipartFile.getSize());
        UserDto currUser = getCurrUser(request);
        // 创建Upload实体对象
        Upload file = FileUpload.getFile(multipartFile, "/file");
        if (Objects.isNull(file)){
            log.info("创建文件失败");
            return ReturnT.FAIL;
        }
        ReturnT<Upload> returnT = saveImage(multipartFile, file);
        if (type == 2){
            Upload content = returnT.getContent();
            //修改用户头像
            User user = userService.getById(currUser.getUserId());
            user.setUserface(content.getPath());
            userService.updateById(user);
            return ReturnT.SUCCESS(content.getPath());
        }
        return returnT;
    }

    /**
     * 保存上传的web格式图片
     */
    private ReturnT saveImage(MultipartFile multipartFile, Upload upload) {
        try {
            // 判断图片是否存在
            Upload uploadSha1 = uploadService.getBySha1(FileUpload.getFileSHA1(multipartFile));
            if (uploadSha1 != null) {
                return ReturnT.SUCCESS(uploadSha1);
            }

            FileUpload.transferTo(multipartFile, upload);
            // 将文件信息保存到数据库中
            uploadService.save(upload);
            return ReturnT.SUCCESS(upload);
        }catch (Exception e){
            e.printStackTrace();
            return ReturnT.FAIL;
        }
    }
}
